<?php
namespace App\Repository;

use App\Model\Order;
use App\Facade\Event;
use App\Event\Order\CreateEvent;

class OrderRepository extends \HyperfStore\Repository
{
    // 放入模型
    public function build()
    {
        return new Order;
    }

    // 创建
    public function create(UserRepository $user, ProductRepository $product, $data)
    {
        $this->model->user()->associate($user->model());
        $this->model->product()->associate($product->model());
        
        $res = $this->exception(function() use($data) {
            return $this->save($data);
        });
        
        if($res)
        {
            Event::dispatch(new CreateEvent($this, $product));
        }
        
        return $res;
    }
    
    // 发货操作
    public function express($name, $code)
    {
        $this->model->status = Order::STATUS_EXPRESS;
        $this->model->express = $name ?? '';
        $this->model->express_code = $code ?? '';
        
        return $this->model->save();
    }
}